package org.zjt.platform.springbootreactivedemo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-06-12 下午9:06
 * @see
 */
@Component
@Slf4j
public class CustomizedWebFilter implements WebFilter ,Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {

        log.info("++++++++++++++++++org.zjt.platform.springbootreactivedemo.config.CustomizedWebFilter.filter++++++++++++++++++++");

        serverWebExchange.getResponse().beforeCommit(() -> {
            log.info("------------beforeCommit--------------");
            return Mono.empty();
        });

        DefaultDataBufferFactory defaultDataBufferFactory = new DefaultDataBufferFactory();
        Mono<DataBuffer> dataBufferMono = Mono.just(defaultDataBufferFactory.wrap("wwwwwwwww".getBytes()));
        serverWebExchange.getResponse().writeWith(dataBufferMono);

        serverWebExchange.getResponse().writeAndFlushWith(Mono.just(dataBufferMono));

        return webFilterChain.filter(serverWebExchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
